// models/user.js
const db = require("./../server/db");
const { generateToken } = require("../utils/jwt");
const { Console } = require("winston/lib/winston/transports");

class User {
  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} 新创建的用户
   */
  static async create(userData) {
    const {
      openid,
      nickname,
      avatar_url,
      gender = 0,
      city,
      province,
      country,
    } = userData;

    const [result] = await db.execute(
      `INSERT INTO users 
       (openid, nickname, avatar_url, gender, city, province, country) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [openid, nickname, avatar_url, gender, city, province, country]
    );

    return {
      id: result.insertId,
      openid,
      nickname,
      avatar_url,
      gender,
      city,
      province,
      country,
    };
  }

  /**
   * 通过openid查找用户
   * @param {string} openid - 微信openid
   * @returns {Promise<Object|null>} 用户对象或null
   */
  static async findByOpenid(openid) {
    const connection = await db.getConnection();
    try {
      const [rows] = await connection.query(
        "SELECT * FROM users WHERE openid = ? LIMIT 1",
        [openid]
      );
      return rows.length ? rows[0] : null;
    } catch (queryErr) {
      console.error("查询错误:", queryErr);
      return queryErr;
    } finally {
      connection.release();
      console.log("数据库连接已释放");
    }
  }

  /**
   * 通过ID查找用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object|null>} 用户对象或null
   */
  static async findById(id) {
    console.log(id)
    const rows = await db.execute(
      "SELECT * FROM users WHERE id = ? LIMIT 1",
      [id]
    );
    return rows.length ? rows[0] : null;
  }

  /**
   * 查找或创建微信用户
   * @param {Object} wechatData - 微信返回的数据
   * @param {Object} userInfo - 用户信息
   * @returns {Promise<Object>} 用户对象
   */
  static async findOrCreateByOpenid(wechatData, userInfo = {}) {
    const { openid } = wechatData;
    let user = await this.findByOpenid(openid);

    if (!user) {
      user = await this.create({
        openid,
        nickname: userInfo.nickName,
        avatar_url: userInfo.avatarUrl,
        gender: userInfo.gender || 0,
        city: userInfo.city,
        province: userInfo.province,
        country: userInfo.country,
      });
    } else {
      // 更新用户信息
      await db.execute(
        `UPDATE users SET 
         nickname = ?, avatar_url = ?, gender = ?, city = ?, province = ?, country = ? 
         WHERE id = ?`,
        [
          userInfo.nickName || user.nickname,
          userInfo.avatarUrl || user.avatar_url,
          userInfo.gender || user.gender,
          userInfo.city || user.city,
          userInfo.province || user.province,
          userInfo.country || user.country,
          user.id,
        ]
      );
    }

    return user;
  }

  /**
   * 生成JWT Token
   * @param {Object} user - 用户对象
   * @returns {string} JWT Token
   */
  static generateToken(user) {
    return generateToken({
      userId: user.id,
      openid: user.openid,
    });
  }

  /**
   * 更新用户最后登录时间
   * @param {number} userId - 用户ID
   * @returns {Promise}
   */
  static async updateLoginTime(userId) {
    await db.execute("UPDATE users SET last_login = NOW() WHERE id = ?", [
      userId,
    ]);
  }
}

module.exports = User;
